﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana
{
    public sealed class FontCache
    {
        private static Logger logger = LogSystem.GetLogger("FontCache");
        private Font font;
        private float defaultReleaseAfterFree = 30f;
        private float lastFreeTime = -1f;
        private Dictionary<Font, FontCache> fontCacheMap;
        public AssetID AssetID { get; private set; }
        public int ReferenceCount { get; private set; }
        public float LastFreeTime
        {
            get{ return lastFreeTime;}
        }
        public float ReleaseAfterFree { get; private set; }
        public string Error { get; private set; }
        public FontCache(AssetID asset, Dictionary<Font, FontCache> map)
        {
            this.AssetID = asset;
            this.fontCacheMap = map;
        }

        public void SetReleaseTimeAfterFree(float t)
        {
            this.defaultReleaseAfterFree = t;
            this.ReleaseAfterFree = t;
        }

        public void Retain()
        {
            ReferenceCount++;
        }

        public void Release()
        {
            ReferenceCount--;
            lastFreeTime = Time.realtimeSinceStartup;
        }

        public void Load(AssetID assetID)
        {
            Scheduler.RunCoroutine(WaitLoad(assetID));
        }

        public bool IsNotNull()
        {
            return this.font != null;
        }

        public Font GetObject()
        {
            return this.font;
        }

        private IEnumerator WaitLoad(AssetID assetID)
        {
            WaitLoadObject waitLoadObject = AssetManager.LoadObject(assetID, typeof(Font));
            yield return waitLoadObject;
            if (!string.IsNullOrEmpty(waitLoadObject.Error))
            {
                this.Error = waitLoadObject.Error;
                yield break;
            }

            this.font = (waitLoadObject.GetObject() as Font);
            if (this.font == null)
            {
                this.Error = string.Format("The asset {0} is not a Font.", assetID);
                yield break;
            }
            ReleaseAfterFree = defaultReleaseAfterFree;

            if (fontCacheMap.ContainsKey(this.font))
            {
                logger.LogWarning("The Font {0} has been loaded.", assetID);
                this.fontCacheMap[this.font] = this;
            }
            else
            {
                this.fontCacheMap.Add(this.font, this);
            }
            yield break;
        }
    }
}

